package com.bite.forum.controller;

import com.bite.forum.common.AppConfig;
import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.exception.ApplicationException;
import com.bite.forum.model.Article;
import com.bite.forum.model.ArticleReply;
import com.bite.forum.model.User;
import com.bite.forum.service.impl.ArticleReplyServiceImpl;
import com.bite.forum.service.impl.ArticleServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Autowired
    ArticleServiceImpl articleService;

    @Autowired
    ArticleReplyServiceImpl articleReplyService;

    @PostMapping("/create")
    public AppResult create(HttpServletRequest request ,
                            @RequestParam("articleId") @NonNull Long articleId ,
                            @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null || user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            throw new ApplicationException(ResultCode.FAILED_USER_BANNED.getMessage());
        }
        Article article = articleService.selectById(articleId);
        // 是否存在，或已删除
        if (article == null || article.getDeleteState() == 1) {
            // 表示已删除或不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 是否封帖
        if (article.getState() == 1) {
            // 表示已封贴
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 构建回复对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId); // 要回复的帖Id
        articleReply.setPostUserId(user.getId()); // 回复的发送者
        articleReply.setContent(content); // 回复的内容
        // 写入回复
        articleReplyService.create(articleReply);
        // 返回结果
        return AppResult.success();
    }
    @GetMapping("/getReplies")
    public AppResult<ArticleReply> getRepliesArticleId(@Param("articleId") @NonNull Long articleId){
       Article article = articleService.selectById(articleId);
       if(article == null){
           log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());

           throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
       }
       List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);

       return AppResult.success(articleReplies);
    }

}


























